package com.novel.system.service.impl;

import com.novel.common.constants.UserConstants;
import com.novel.common.exception.business.BusinessException;
import com.novel.common.utils.StringUtils;
import com.novel.system.domain.SysRole;
import com.novel.system.domain.SysRoleMenu;
import com.novel.system.mapper.SysRoleMapper;
import com.novel.system.mapper.SysRoleMenuMapper;
import com.novel.system.mapper.SysUserRoleMapper;
import com.novel.system.service.SysRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 角色 业务层处理
 *
 * @author novel
 * @date 2019/5/8
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {
    private final SysRoleMapper roleMapper;
    private final SysRoleMenuMapper roleMenuMapper;
    private final SysUserRoleMapper userRoleMapper;

    public SysRoleServiceImpl(SysRoleMapper roleMapper, SysRoleMenuMapper roleMenuMapper, SysUserRoleMapper userRoleMapper) {
        this.roleMapper = roleMapper;
        this.roleMenuMapper = roleMenuMapper;
        this.userRoleMapper = userRoleMapper;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRoleKeys(Long userId) {
        List<SysRole> perms = roleMapper.selectRolesByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms) {
            permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
        }
        return permsSet;
    }

    /**
     * 根据条件分页查询角色数据
     *
     * @param role 角色信息
     * @return 角色数据集合信息
     */
    @Override
    public List<SysRole> selectRoleList(SysRole role) {
        return roleMapper.selectRoleList(role);
    }

    /**
     * 新增保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean insertRole(SysRole role) {
        // 新增角色信息
        roleMapper.insertRole(role);
        return insertRoleMenu(role) > 0;
    }

    /**
     * 修改保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public boolean updateRole(SysRole role) {
        // 修改角色信息
        roleMapper.updateRole(role);
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(role.getId());
        return insertRoleMenu(role) > 0;
    }

    @Override
    public boolean deleteRoleByIds(Long[] ids) {
        for (Long roleId : ids) {
            SysRole role = selectRoleById(roleId);
            if (countUserRoleByRoleId(roleId) > 0) {
                throw new BusinessException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }
        return roleMapper.deleteRoleByIds(ids) > 0;
    }


    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    private int insertRoleMenu(SysRole role) {
        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<>();
        if (role != null && role.getMenuIds() != null && role.getMenuIds().length > 0) {
            for (Long menuId : role.getMenuIds()) {
                SysRoleMenu rm = new SysRoleMenu();
                rm.setRoleId(role.getId());
                rm.setMenuId(menuId);
                list.add(rm);
            }
        }
        if (list.size() > 0) {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }

    /**
     * 通过角色ID查询角色
     *
     * @param roleId 角色ID
     * @return 角色对象信息
     */
    @Override
    public SysRole selectRoleById(Long roleId) {
        return roleMapper.selectRoleById(roleId);
    }


    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int countUserRoleByRoleId(Long roleId) {
        return userRoleMapper.countUserRoleByRoleId(roleId);
    }

    @Override
    public Map<String, Object> selectRolesByUserId(Long userId) {
        Map<String, Object> map = new HashMap<>(2);
        SysRole sysRole = new SysRole();
        sysRole.setStatus("0");
        map.put("roles", roleMapper.selectRoleList(sysRole));
        if (StringUtils.isNotNull(userId)) {
            List<SysRole> sysRoles = roleMapper.selectRolesByUserId(userId);
            List<Long> roleIds = new ArrayList<>();
            sysRoles.forEach(item -> roleIds.add(item.getId()));
            map.put("roleIds", roleIds);
        }
        return map;
    }


    /**
     * 校验角色名称是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public String checkRoleNameUnique(SysRole role) {
        long roleId = StringUtils.isNull(role.getId()) ? -1L : role.getId();
        List<SysRole> roleList = roleMapper.checkRoleNameUnique(role.getRoleName());
        if (roleList != null) {
            for (SysRole sysRole : roleList) {
                if (StringUtils.isNotNull(sysRole) && sysRole.getId() != roleId) {
                    return UserConstants.ROLE_NAME_NOT_UNIQUE;
                }
            }
        }
        return UserConstants.ROLE_NAME_UNIQUE;
    }

    /**
     * 校验角色权限是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public String checkRoleKeyUnique(SysRole role) {
        long roleId = StringUtils.isNull(role.getId()) ? -1L : role.getId();
        List<SysRole> roleList = roleMapper.checkRoleKeyUnique(role.getRoleKey());
        if (roleList != null) {
            for (SysRole sysRole : roleList) {
                if (StringUtils.isNotNull(sysRole) && sysRole.getId() != roleId) {
                    return UserConstants.ROLE_KEY_NOT_UNIQUE;
                }
            }
        }
        return UserConstants.ROLE_KEY_UNIQUE;
    }
}
